﻿using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using ServiceCore;
using ServiceCore.Tool.ES;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using static ServiceCore.Tool.ES.es_cloud_product; 

namespace Customer.Bussiness_Service
{
    public interface Icloud_product_service
    {
        /// <summary>
        /// 添加云商品库商品
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save_cloud_product(cloud_product Params);
        /// <summary>
        /// 从云商品库中拉取商品数据
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel clone_customer_product(string id);
        /// <summary>
        /// 查询云商品库数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultObjModel get_cloud_product_list(cloud_product_search query);
        /// <summary>
        /// 根据条码查询
        /// </summary>
        /// <param name="codebar"></param>
        /// <returns></returns>
        ResultObjModel get_codebar_product(string codebar);
        ResultObjModel get_cate_list();
        ResultObjModel get_structure_template(string name);
        /// <summary>
        /// 开始同步云商品库数据
        /// </summary>
        /// <returns></returns>
        Task<ResultObjModel> start_synchronization_rk_stock();
        /// <summary>
        /// 删除云商品库数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        ResultObjModel del_cloud_product(string id);
    }
    public class cloud_product_service : Icloud_product_service
    {

        public string config_position { get { return _appSettingConfig["rk_structure_template_config"].ToString(); } }

        private static string[] DefaultCateName = new string[] { "饮料", "其他" };  

        private readonly IToole_DI _tool;
        private readonly Ies_cloud_product _es_service;
        private readonly IHttpContextAccessor _context;
        private readonly IConfiguration _appSettingConfig;

        public cloud_product_service(IToole_DI Tool, Ies_cloud_product EsService, IHttpContextAccessor Context, IConfiguration AppSettingConfig)
        {
            _tool = Tool;
            _es_service = EsService;
            _context = Context;
            _appSettingConfig = AppSettingConfig;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="TempInfo"></param>
        private List<Structure_Template> ReadTemplate()
        {
            try
            {
                string File_Path = config_position + "/Config.json";
                using (FileStream fS = new FileStream(File_Path, FileMode.Open, FileAccess.Read))
                {
                    StreamReader sr = new StreamReader(fS, Encoding.UTF8);//设定读写的编码                 
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    string read_data =  sr.ReadToEnd();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Structure_Template>>(read_data);
                } 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取模板信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_structure_template(string name)
        {
            return CoreStartDo.ResultAction(result =>
            {

                var list = ReadTemplate();
                result.code = 0;
                result.msg = "success";
                result.data = !list.Where(s => s.CateName == name).Any() ? list.Where(s => s.CateName == "其他").ToList() : list.Where(s => s.CateName == name).ToList();
                return result;
            });
        }
        /// <summary>
        /// 添加云商品库商品
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        public ResultObjModel save_cloud_product(cloud_product Params)
        {
            Params.is_rk_cloud = true;
            Params.baseuserid = "rk_cloud";
            return save_product(Params);
        } 
        /// <summary>
        /// 从云商品库中拉取商品数据
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        public ResultObjModel clone_customer_product(string id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                //var have_item = _es_service.get_es_model(s => s.Must(sq =>
                //   sq.Term(c => c.Field(d => d.baseuserid).Value(_tool.di_user.RK_USER.BaseUserId))
                //&& sq.Term(c => c.Field(d => d.source_id).Value(id))));
                if (_tool.di_user.RK_USER == null || string.IsNullOrWhiteSpace(_tool.di_user.RK_USER.BaseUserId))
                {
                    result.code = 1;
                    result.msg = "token异常";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "云商品库ID未上报";
                    return result;
                }
                var have_item = _tool.di_db.Get_rk_List<Product>("select top 1 * from Product where baseuserid=@baseuserid and ProductId=@ProductId", new { baseuserid = _tool.di_user.RK_USER.BaseUserId, ProductId = id }).FirstOrDefault();
                if (have_item != null)
                {
                    result.code = 1;
                    result.msg = "当前商品已添加到本地商品库";
                    return result;
                }
                cloud_product product_mod = _es_service.get_es_model(id);
                if (product_mod == null)
                {
                    result.code = 1;
                    result.msg = "云商品库数据不存在";
                    return result;
                }
                Product new_product = new Product()
                {
                    Id = _tool.di_getid.IGet_SnowFlake_Id,
                    BaseUserId = _tool.di_user.RK_USER.BaseUserId,
                    Brand = product_mod.Brand,
                    CategoryId = product_mod.CategoryId,
                    codeBar = product_mod.codeBar,
                    CreateBy = _tool.di_user.RK_USER.BaseUserId,
                    CreateOn = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Def_Cost = 0,
                    Des = product_mod.Des,
                    Img = product_mod.Img,
                    IsDelete = false,
                    Keyword = product_mod.Keyword,
                    Name = product_mod.Name,
                    Price = Convert.ToDecimal(product_mod.Price.Value),
                    ProductId = id,
                    Spec = product_mod.Spec,
                    SrcProductId = id,
                    StructureContent = product_mod.StructureContent,
                    TemplateContent = product_mod.TemplateContent,
                    Type = product_mod.Type,
                    UpdateOn = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    UpdateBy = _tool.di_user.RK_USER.BaseUserId
                };
                int addproduct = _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<Product>(), new_product);//.Add(new_product);
                if (addproduct > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "添加到本地库失败";
                }
                return result;
            });
        } 
        /// <summary>
        /// 保存商品
        /// </summary>
        /// <returns></returns>
        private ResultObjModel save_product(cloud_product Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.Name))
                {
                    result.code = 1;
                    result.msg = "商品标题不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.CategoryId))
                {
                    result.code = 1;
                    result.msg = "商品类型不能为空";
                    return result;
                }
                //if (string.IsNullOrWhiteSpace(Params.Brand))
                //{
                //    result.code = 1;
                //    result.msg = "品牌不能为空";
                //    return result;
                //}
                if (!Params.Price.HasValue)
                {
                    result.code = 1;
                    result.msg = "设置建议价格不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.Img))
                {
                    result.code = 1;
                    result.msg = "必须上传图片";
                    return result;
                }
                if (!Params.is_rk_cloud.HasValue)
                {
                    result.code = 1;
                    result.msg = "上传参数错误ERROR";
                    return result;
                }
                Category selected_category = _tool.di_db.Get_rk_List<Category>("select top 1 * from Category where Id=@CategoryId", new { CategoryId = Params.CategoryId }).FirstOrDefault();
                if (selected_category == null)
                {
                    result.code = 1;
                    result.msg = "所选类型不存在";
                    return result;
                }
                if (!string.IsNullOrWhiteSpace(Params.TemplateContent))
                {
                    var Template = ReadTemplate().Where(s => s.Tid == Params.TemplateContent.ToString()).FirstOrDefault();
                    if (Template != null)
                    {
                        Params.TemplateContent = Newtonsoft.Json.JsonConvert.SerializeObject(Template);
                    }
                }
                if (string.IsNullOrWhiteSpace(Params.Id))
                {
                    //直接添加数据
                    Params.add_time = DateTime.Now;
                    Params.add_user = _tool.di_user.USER.uid;
                    Params.Id = _tool.di_getid.IGet_SnowFlake_Id; 
                    Params.Category_name = selected_category.Name;
                    Params.product_state = 1;
                     

                    if (string.IsNullOrWhiteSpace(Params.source_id))
                    {
                        Params.source_id = Params.Id;
                    }
                    if (string.IsNullOrWhiteSpace(Params.codeBar))
                    {
                        Params.codeBar = "none";
                    }
                    Params.edit_time = DateTime.Now;
                    object addresult = _es_service.Add_Item(Params);
                    result.code = 0;
                    result.msg = "保存成功";
                    result.data = addresult;
                }
                else
                {
                    cloud_product update_doc = _es_service.get_es_model(Params.Id);
                    if (update_doc == null)
                    {
                        result.code = 1;
                        result.msg = "修改数据不存在";
                        return result;
                    } 
                    update_doc.Img = Params.Img;
                    update_doc.thumbnail = Params.thumbnail;
                    update_doc.Des = Params.Des;
                    update_doc.Brand = Params.Brand;
                    update_doc.CategoryId = Params.CategoryId;
                    update_doc.Category_name = Params.Category_name;
                    update_doc.codeBar = Params.codeBar;
                    update_doc.Def_Cost = Params.Def_Cost;
                    update_doc.ext_params = Params.ext_params;
                    update_doc.Keyword = Params.Keyword;
                    update_doc.Name = Params.Name;
                    update_doc.old_params = Params.old_params;
                    update_doc.other_search = $"{selected_category.Name},{Params.Brand},{Params.Spec},{Params.Type}";
                    update_doc.pic_des = Params.pic_des;
                    update_doc.Price = Params.Price;
                    update_doc.Spec = Params.Spec;
                    update_doc.Type = Params.Type;
                    update_doc.StructureContent = Params.StructureContent;
                    update_doc.TemplateContent = Params.TemplateContent;
                    if (string.IsNullOrWhiteSpace(Params.codeBar))
                    {
                        Params.codeBar = "none";
                    }
                    update_doc.edit_time = DateTime.Now;
                    object addresult = _es_service.Update_row(update_doc);
                    result.code = 0;
                    result.msg = "保存成功";
                    result.data = addresult;
                }
                return result;
            });
        } 
        /// <summary>
        ///  根据条码获取商品信息
        /// </summary>
        /// <param name="codebar"></param>
        /// <returns></returns>
        public ResultObjModel get_codebar_product(string codebar)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var codebar_mod = _es_service.get_es_model(sq =>
                sq.Must(c => c.Term(d => d.Field(e => e.codeBar).Value(codebar))
                 && c.Term(d => d.Field(e => e.is_rk_cloud).Value(true))
                ));
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    codebar_mod.codeBar,
                    codebar_mod.Name,
                    codebar_mod.Img,
                    codebar_mod.Price,
                    codebar_mod.Id
                };
                return result;
            });
        }
        /// <summary>
        /// 查询云商品库数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel get_cloud_product_list(cloud_product_search query)
        {
            return CoreStartDo.ResultAction(result =>
            {
                List<string> have_product = null;
                var mod = _es_service.Es_query(query, "", (a, b) =>
                {
                    if (have_product == null)
                    {
                        if (_tool.di_user.RK_USER == null || string.IsNullOrWhiteSpace(_tool.di_user.RK_USER.BaseUserId))
                        {
                            have_product = new List<string>();
                        }
                        else
                        {
                            have_product = _tool.di_db.Get_rk_List<string>("select ProductId from Product where baseuserid=@baseuserid and ProductId in @ProductIds", new { baseuserid = _tool.di_user.RK_USER.BaseUserId, ProductIds = a.Select(s => s.Id).ToArray() }).ToList();
                        }
                    }
                    if (have_product.Contains(b))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                });
                result.code = 0;
                result.msg = "success";
                result.data = mod;
                return result;
            });  
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_cate_list()
        {
            return CoreStartDo.ResultAction(result =>
            {
                var cate_list = _tool.di_db.Get_rk_List<Category>("select * from Category where Isprivate=0 and IsDelete=0 order by sort asc", null);
                result.code = 0;
                result.msg = "success";
                result.data = from o in cate_list
                              select new
                              {
                                  o.Id,
                                  o.Name
                              };
                return result;
            });
        }
        /// <summary>
        /// 开始同步云商品库数据
        /// </summary>
        /// <returns></returns>
        public async Task<ResultObjModel> start_synchronization_rk_stock()
        {
            var start_task = await Task.Run(() =>
           {
               return CoreStartDo.ResultAction(result =>
                {
                    List<Product> product_list = _tool.di_db.Get_rk_List<Product>("select * from Product where baseuserid=@baseuserid", new { baseuserid = "RK" }).ToList();
                    int success = 0;
                    int fail = 0;
                    int repetition = 0;
                    foreach (var item in product_list)
                    {
                        cloud_product in_cloud;
                        try
                        {
                            in_cloud = _es_service.get_es_model(s => s.Must(t => t.Term(d => d.Field(a => a.Id).Value(item.Id))));
                        }
                        catch {
                            in_cloud = null;
                        }
                        if (in_cloud != null)
                        {
                            repetition++;
                            continue;
                        }
                        var info = synchronization_save_product(new cloud_product()
                        {
                            Id = item.Id,
                            add_user = "server",
                            Brand = item.Brand,
                            CategoryId = item.CategoryId,
                            codeBar = item.codeBar,
                            Def_Cost = Convert.ToDouble(item.Def_Cost),
                            Des = item.Des,
                            Img = item.Img,
                            Keyword = item.Keyword,
                            Name = item.Name,
                            Price = Convert.ToDouble(item.Price),
                            Spec = item.Spec,
                            StructureContent = item.StructureContent,
                            TemplateContent = item.TemplateContent,
                            thumbnail = item.thumbnail,
                            Type = item.Type
                        });
                        if (info.code == 0)
                        {
                            success++;
                        }
                        else {
                            fail++;
                        }
                    }
                    result.code = 0;
                    result.msg = "success";
                    result.data = new
                    {
                        db_count = product_list.Count(),
                        success_count = success,
                        fail_count = fail,
                        repetition_count = repetition,
                    };
                    return result;
                });
           });
            return start_task;
        }

        /// <summary>
        /// 保存商品
        /// </summary>
        /// <returns></returns>
        private ResultObjModel synchronization_save_product(cloud_product Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                Category selected_category = _tool.di_db.Get_rk_List<Category>("select top 1 * from Category where Id=@CategoryId", new { CategoryId = Params.CategoryId }).FirstOrDefault();
                if (selected_category == null)
                {
                    result.code = 1;
                    result.msg = "所选类型不存在";
                    return result;
                }
                //直接添加数据
                Params.add_time = DateTime.Now;
                Params.edit_time = DateTime.Now;
                Params.Category_name = selected_category.Name;
                Params.product_state = 1;
                Params.is_rk_cloud = true;
                Params.baseuserid = "rk_cloud";
                if (string.IsNullOrWhiteSpace(Params.source_id))
                {
                    Params.source_id = Params.Id;
                }
                if (string.IsNullOrWhiteSpace(Params.codeBar))
                {
                    Params.codeBar = "none";
                }
                object addresult = _es_service.Add_Item(Params);
                result.code = 0;
                result.msg = "保存成功"; 
                return result;
            });
        }
        /// <summary>
        /// 删除云商品库数据
        /// </summary>
        /// <returns></returns>
        public ResultObjModel del_cloud_product(string id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var obj = _es_service.Es_delete(id);
                result.code = 0;
                result.msg = "删除成功";
                result.data = obj;
                return result;
            });
        }
    }
}
